<?php

/**
 * user actions.
 *
 * @package    project_midnight
 * @subpackage user
 * @author     AlvaroLara
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions
{

  public function preExecute()
  {
    parent::preExecute();
    sfContext::getInstance()->getConfiguration()->loadHelpers('I18N');
  }
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    $this->forward('default', 'module');
  }

  public function executeLogin(sfWebRequest $request)
  {
    $this->form = new LoginForm();

    if (strcmp($request->getMethod(),"get") == 0)
    {
      return $this->renderPartial('user/login',array('form' => $this->form));
    }

    if ($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter('signin'));
      if ($this->form->isValid())
      {
        $values = $this->form->getValues();
        $this->getUser()->signin($values['user']);

        // always redirect to a URL set in app.yml
        // or to the referer
        // or to the homepage
      }
      else
      {
        $this->getUser()->setFlash('error',__('Username and/or password incorrect'));
      }
        $this->redirect('idea/index');
    }

    return sfView::NONE;
  }

  public function executeSignout($request)
  {
    $this->getUser()->signOut();

    $this->redirect('@homepage');
  }

  public function executeUserInfo(sfWebRequest $request)
  {
    if($this->getUser()->isAuthenticated())
    {
      return $this->renderPartial('user/info');
    }
  }

  public function executeNew(sfWebRequest $request)
  {
    $this->form = new ApplicationUserForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->form = new ApplicationUserForm();

    $this->processForm($request,$this->form);

    $this->setTemplate('new');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $notice = $form->getObject()->isNew() ? 'Welcome to the cloud!' : 'Hi there again';
      try
      {
       $ApplicationUser = $form->save();
      }
      catch (Exception $e)
      {
        $this->getUser()->setFlash('error',__('Sorry but the username is already in use, please choose another.'));
        $this->redirect('user/new');
      }

      $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $ApplicationUser)));

      $this->getUser()->setFlash('notice', __($notice));

      $this->getUser()->signin($ApplicationUser);

      $this->redirect('@homepage');
    }
    else
    {
      $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
    }
  }

}
